package com.mmall.mmall002.filter;


import org.springframework.http.HttpRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserFilter  implements Filter{

    /**
     * 配置一个过滤器 用来拦截未登录用户的添加购物车请求
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse , FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession  session = request.getSession();

        if(session.getAttribute("user") == null){
            request.setAttribute("error","请登录后再进行操作!");
            request.getRequestDispatcher("/login").forward(request,response); //转发到登录界面
//            response.sendRedirect("/login"); //重定向到登录界面
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

}
